<template>
  <div class="wrapper">
    <card _Title="用户信息" />
    <Form :model="formItem" :rules="rules" ref="form" :label-width="100">
      <FormItem label="头像">
        <Avatar v-if="formItem.avatarUrl" :src="commonUrl + formItem.avatarUrl" size="80" />
        <Avatar v-else src="https://i.loli.net/2017/08/21/599a521472424.jpg" icon="person" size="80" />
        <Upload :action="uploadFileUrl" :file-list="fileList" :limit="1" :on-success="handleSuccess"
          :format="['jpg', 'jpeg', 'png']" :show-upload-list="false" :headers="headers" class="upload-file-uploader"
          ref="fileUpload">
          <Button class="mt_10" v-if="disabled">上传头像</Button>
        </Upload>
      </FormItem>
      <FormItem label="昵称" prop="nickName">
        <span v-if="!disabled">{{ formItem.nickName }}</span>
        <Input v-else class="wrapper-user-name" style="width:200px" v-model="formItem.nickName" placeholder="" />
      </FormItem>
      <FormItem label="手机号修改" prop="phone">
        <span v-if="!disabled">{{ formItem.phone }}</span>
        <Input v-else class="wrapper-user-name" style="width:200px" v-model="formItem.phone" placeholder="" />
      </FormItem>
      <FormItem label="真实姓名" v-if="roles == 'writers'">
        <span v-if="!disabled">{{ formItem.realName }}</span>
        <Input v-else class="wrapper-user-name" style="width:200px" v-model="formItem.realName" placeholder="" />
      </FormItem>
      <FormItem label="身份证号" v-if="roles == 'writers'">
        <span v-if="!disabled">{{ formItem.idCard }}</span>
        <Input v-else class="wrapper-user-name" style="width:200px" v-model="formItem.idCard" placeholder="" />
      </FormItem>
      <FormItem label="技能选择" v-if="roles == 'writers'">
        <span v-if="!disabled">{{ formItem.skill }}</span>
        <Select v-else  style="width:200px" v-model="formItem.skill" placeholder="请选择需求类型">
          <Option value="ui">ui</Option>
          <Option value="ppt">ppt</Option>
          <Option value="other">其他</Option>
        </Select>
      </FormItem>
      <FormItem label="资质信息上传" v-if="roles == 'writers'">
        <FileUpload :disabled="!disabled" @input="FileUploadInput" :value="formItem.kefuUrl"></FileUpload>
      </FormItem>
      <FormItem label="验证码校验" v-if="disabled">
        <i-input type="text" v-model="formItem.code" style="width:200px" clearable placeholder="手机验证码">
          <Button slot="append" @click="sendCode">{{ codeMsg }}</Button>
        </i-input>
      </FormItem>

      <!-- <FormItem label="生日">
        <DatePicker type="date" placeholder="选择您的生日" v-model="formItem.birthday"></DatePicker>
      </FormItem> -->
      <!-- <FormItem label="性别">
        <RadioGroup v-model="formItem.sex" type="button" button-style="solid">
          <Radio :label="1">男</Radio>
          <Radio :label="0">女</Radio>
        </RadioGroup>
      </FormItem> -->
      <FormItem v-if="!disabled">
        <Button type="primary" @click="disabled=true">编辑</Button>
      </FormItem>
      <FormItem v-else>
        <Button type="primary" @click="save">提交</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import { sendSMSPhone, updatePhone } from '@/api/writer/index';
import { editMemberInfo } from '@/api/account.js';
import * as RegExp from "@/plugins/RegExp.js";

import storage from '@/plugins/storage.js';

export default {
  name: 'Profile',
  data() {
    return {
      rules: { // 验证规则
        nickName: [{ required: true, message: '用户昵称不能为空' }, { max: 16, message: '用户昵称不能超过15个字符' }],
        phone: [
          { required: true, message: "请输入手机号码" },
          {
            pattern: RegExp.mobile,
            trigger: "blur",
            message: "请输入正确的手机号",
          },
        ],
      },
      roles: storage.getItem("roles"), // 角色列表
      formItem: {}, // 表单数据
      commonUrl: BASE.API_DEV.buyer, // 图片服务器地址
      uploadFileUrl: BASE.API_DEV.buyer + "/common/upload", // 上传文件服务器地址
      headers: {
        Authorization: storage.getItem("accessToken"),
      },
      fileList: [], // 上传文件列表
      codeMsg: "获取验证码",
      time: 60,
      interval: null,
      disabled: false, // 是否可编辑
    }
  },
  mounted() {
    this.formItem = JSON.parse(storage.getItem('userInfo'))
    console.log(this.formItem, 'this.formItem');

  },
  methods: {
    save() { // 保存
      this.$refs.form.validate(valid => {
        if (valid) {
          let params = {
            avatarUrl: this.formItem.avatarUrl,
            nickName: this.formItem.nickName,
            phone: this.formItem.phone,
            ...this.formItem
          }
          if (JSON.parse(storage.getItem('userInfo')).phone != this.formItem.phone) {
            if (this.formItem.code == "") {
              this.$Message.warning("修改手机号后请获取验证码，验证手机号");
              return;
            }
            updatePhone(params).then(res => {
              this.$Message.success('修改个人资料成功')
              storage.setItem('userInfo', JSON.stringify(res.data))
              this.$router.go(0)
            })
          } else {
            editMemberInfo(params).then(res => {
              if (res.code == 200) {
                this.$Message.success('修改个人资料成功')
                storage.setItem('userInfo', JSON.stringify(res.data))
                this.$router.go(0)
              }
            })
          }

        }
      })
    },
    handleSuccess(res, file) { // 上传成功
      this.$set(this.formItem, 'avatarUrl', res.fileName)
    },
    // 发送短信验证码
    sendCode() {
      if (this.time === 60) {
        if (this.formItem.phone === "") {
          this.$Message.warning("请先填写手机号");
          return;
        }
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (phoneRegex.test(this.formItem.phone)) {
          let params = {
            phone: this.formItem.phone,
          };
          sendSMSPhone(params).then((res) => {
            if (res.code == 200) {
              this.$Message.success("验证码发送成功");
              this.formItem.code = res.data;
              let that = this;
              this.interval = setInterval(() => {
                that.time--;
                if (that.time === 0) {
                  that.time = 60;
                  that.codeMsg = "重新发送";
                  clearInterval(that.interval);
                } else {
                  that.codeMsg = that.time;
                }
              }, 1000);
            } else {
              this.$Message.warning(res.msg);
            }
          });
        } else {
          this.$Message.warning("请输入正确的手机号");
        }
      }
    },
    FileUploadInput(val) {
      this.formItem.kefuUrl = val
    },
  }

}
</script>

<style scoped lang="scss"></style>
